import { getCartList, CartUpdate, delSelect } from '@/api/cart'

export default {
  namespaced: true,
  state () {
    return {
      cartList: [] // 购物车列表
    }
  },
  mutations: {
    setCartList (state, newObj) {
      state.cartList = newObj
    },
    // 点击小选，修改状态
    toggleCheck (state, goodsId) {
      // 找到哪个小选
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    // 点击全选，重置状态
    toggleAllCheck (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    // 前面修改状态
    changeCount (state, { goodsId, value }) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = value
    }
  },
  actions: {
    // 获取购物车列表
    async getCartList (context) {
      const { data } = await getCartList()
      console.log(data)
      // 添加复选框的状态
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', data.list)
    },
    // 数字框修改数量
    async changeCount (context, obj) {
      // 后台数据更新成功
      const { value, goodsId, skuId } = obj
      await CartUpdate(goodsId, value, skuId)
      context.commit('changeCount', { goodsId, value })
    },
    // 删除购物车
    async handleDel (context) {
      const delCartList = context.getters.selCartList
      const cartIds = delCartList.map(item => item.id)
      await delSelect(cartIds)

      // 重新获取当前购物车列表
      context.dispatch('getCartList')
    }
  },
  getters: {
    // 商品总数
    cartTotal (state) {
      return state.cartList.reduce((sum, item, index) => sum + item.goods_num, 0)
    },

    // 选中的商品列表
    selCartList (state) {
      const selCartList = state.cartList.filter(item => item.isChecked)
      return selCartList
    },

    // 选中商品的总数
    selCartTotal (state, getters) {
      return getters.selCartList.reduce((sum, item, index) => sum + item.goods_num, 0)
    },

    // 选中商品的总价
    selCartPrice (state, getters) {
      return getters.selCartList.reduce((sum, item, index) => sum + item.goods_num * item.goods.goods_price_min, 0)
    },

    // 全选状态
    isCheckedAll (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
